package com.mf.controller.basic;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.mf.aspect.debounces.Debounce;
import com.mf.aspect.logApi.LogApi;
import com.mf.constant.ConstantPermission;
import com.mf.entity.dto.basic.webPage.DtoWebMenu;
import com.mf.entity.req.basic.ReqLogin;
import com.mf.entity.vo.basic.VoLogin;
import com.mf.entity.vo.basic.VoUserMenuAndPermission;
import com.mf.result.Result;
import com.mf.service.basic.ServiceAuth;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author: lmf
 * @Create: 2025/5/8 13:19
 * @module
 */
@RestController
@RequestMapping("auth" )
@Tag(name = "权限认证(登录相关)" )
@Debounce
public class ControllerAuth {
    @Resource
    private ServiceAuth serviceAuth;

    @Operation(summary = "登录" )
    @PostMapping("login" )
    @LogApi("登录" )
    public Result<VoLogin> login(@Validated @RequestBody ReqLogin reqLogin) {
        return Result.success(serviceAuth.login(reqLogin));
    }

    @Operation(summary = "获取用户菜单及权限" )
    @GetMapping("getUserMenuAndPermission" )
    @SaCheckLogin
    public Result<VoUserMenuAndPermission> getUserMenuAndPermission() {
        Object json = StpUtil.getSession().get(ConstantPermission.FRONT_MENU);
        // 手动反序列化
        List<DtoWebMenu> dtoWebMenus = JSON.parseObject((String) json, new TypeReference<List<DtoWebMenu>>() {
        });
        return Result.success(VoUserMenuAndPermission
                .builder()
                .permissions(StpUtil.getPermissionList())
                .menu(dtoWebMenus)
                .build());
    }


    @Operation(summary = "登出" )
    @GetMapping("logout" )
    @LogApi("登出" )
    public Result<String> logout() {
        StpUtil.logout();
        return Result.success("登出成功" );
    }

    @Operation(summary = "判断是否登录" )
    @GetMapping("isLogin" )
    public Result<Boolean> isLogin() {
        return Result.success(StpUtil.isLogin());
    }

    @Operation(summary = "获取用户权限" )
    @GetMapping("getPermissions" )
    @SaCheckLogin
    public Result<List<String>> getPermissions() {
        return Result.success(StpUtil.getPermissionList());
    }


}
